#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdint.h>
#include <string>
#include <memory>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>

const int BUFFERSIZE = 128;
class UdpClient
{
public:
    UdpClient(std::string ip,uint16_t port)
        :_sockfd(-1)
        ,_server_port(port)
        ,_server_ip(ip)
    {

    }
    void Start()
    {
        std::string msg;
        //目标服务器信息
        struct sockaddr_in peer;
        memset(&peer,'\0',sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(_server_port);
        peer.sin_addr.s_addr = inet_addr(_server_ip.c_str());

        while(true)
        {
            std::cout << "Please Enter# ";
            getline(std::cin,msg);
            sendto(_sockfd,msg.c_str(),msg.size(),0,(struct sockaddr*)&peer,sizeof(peer));


            char buffer[BUFFERSIZE] = {0};
            struct sockaddr_in tmp;
            socklen_t len = sizeof(tmp);
            ssize_t size = recvfrom(_sockfd,buffer,sizeof(buffer) - 1,0,(struct sockaddr*)&tmp,&len);
            if(size < 0)
            {
                std::cout << "recvfrom error!!" << std::endl;
            }
            buffer[size] = '\0';
            std::cout << buffer << std::endl;
        }
    }
    bool InitClient()
    {
        //创建套接字
        _sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd < 0)
        {
            std::cout << "create sockfd error!!" << std::endl;
            return false;
        }
        return true;
    }
    ~UdpClient()
    {
        if(_sockfd >= 0)
        {
            close(_sockfd);
        }
    }
private:
    int _sockfd;
    uint16_t _server_port;      //服务器端口号
    std::string _server_ip;     //服务器ip
};

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }
    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);
    UdpClient* clt = new  UdpClient(serverip,serverport);
    clt->InitClient();
    clt->Start();
    return 0;
}